import { getRouteData } from '@/api';

export const createRoute = () => {
  return new Promise((resolve, reject) => {
    getRoute().then(res => {
      const route = listToTree(res, 0);
      if (route.length > 0) {
        resolve(route)
      } else {
        reject([]);
      }
    });
  })
}
// 获取路由数据
const getRoute = () => {
  return new Promise((resolve, reject) => {
    getRouteData().then(res => {
      if (res.code === 200) {
        resolve(res.data);
      } else {
        reject(new Error('数据错误'));
      }
    })
  });
}

// 递归生成树形数据
const listToTree = (listData, pId) => {
  const itemArr = [];
  for (let i = 0; i < listData.length; i++) {
    const item = listData[i];
    if (item.pid === pId) {
      const newNode = {
        path: item.path,
        name: item.name,
        component: () => loadComponent(item.component),
        meta: item.meta
      };
      newNode.children = listToTree(listData, item.id);
      itemArr.push(newNode);
    }
  }
  return itemArr;
}

const loadComponent = (component) => {
  return (resolve) => require([`../views/${component}`], resolve)
}

export const getRoutePermission = (data, path) => {
  return filterTree(path, data);
}
export const filterTree = (path, data) => {
  if (path === '/' || path === '/login' || path === '/404') {
    return true;
  }
  const list = [];
  const treeToList = (treeData) => {
    for (const v of treeData) {
      list.push(v);
      if (v.children && v.children.length > 0) {
        treeToList(v.children);
      }
    }
  };
  treeToList(data);
  const index = list.findIndex(i => i.path === path);
  if (index > -1) {
    return true;
  } else {
    return false;
  }
}
